// 浏览器web页面获取用户位置信息

const webgetlocal = (key: string = '20bc8fa3f1034dffde3ea0db1ea72d3f') => {
	return new Promise((resolve, reject) => {
		let errorMessage = '';
		let location = {
			latitude: 0,
			longitude: 0,
		};
		navigator.geolocation.getCurrentPosition(
			position => {
				location = {
					latitude: position.coords.latitude,
					longitude: position.coords.longitude,
				};
				errorMessage = '';
				// 使用高德地图与经纬度获取用户位置信息
				const url = `https://restapi.amap.com/v3/geocode/regeo?key=${key}&location=${position.coords.longitude},${position.coords.latitude}&output=json&radius=0&extensions=base`;
				fetch(url)
					.then(res => res.json())
					.then(data => {
						let obj = {
							latitude: position.coords.latitude,
							longitude: position.coords.longitude,
							address: data.regeocode.formatted_address,
						};
						resolve(obj);
					});
			},
			error => {
				console.log(error, 222222222);
				switch (error.code) {
					case error.PERMISSION_DENIED:
						errorMessage = '用户拒绝了地理定位请求。请切换浏览器重试';
						break;
					case error.POSITION_UNAVAILABLE:
						errorMessage = '位置信息不可用。请切换浏览器重试';
						break;
					case error.TIMEOUT:
						errorMessage = '请求用户地理位置超时。请切换浏览器重试';
						break;
					default:
						errorMessage = '发生未知错误。请切换浏览器重试';
						break;
				}
				reject(errorMessage);
			},
			{
				enableHighAccuracy: true, // 启用高精度模式
				timeout: 10000, // 5 秒超时
				maximumAge: 0, // 不使用缓存位置
			},
		);
	});
};

export default webgetlocal;
